package com.google.code.jmarias.common.action;

import com.google.code.jmarias.common.AbstractUser;
import com.google.code.jmarias.common.Card;
import com.google.code.jmarias.common.NewTable;
import java.lang.reflect.Field;
import java.util.Arrays;

/**
 *
 * @author Ondrej Michal
 */
public abstract class GameAction extends AbstractAction implements Cloneable {

    public abstract void updateTable(NewTable table, AbstractUser user);

    public GameAction hideCards() {
        try {
            GameAction result = (GameAction) super.clone();
            for (Field field : result.getClass().getDeclaredFields()) {
                if (field.getType().isAssignableFrom(Card.class)) {
                    field.setAccessible(true);
                    field.set(result, Card.createHiddenCard());
                } else if (field.getType().isArray()) {
                    field.setAccessible(true);
                    Object[] array = (Object[]) field.get(result);
                    // pole je potreba zkopirovat, protoze clone neprovadi hloubkovou kopii,
                    // jinak by se skryti karet provedlo i na puvodnim objektu
                    Object[] copy = Arrays.copyOf(array, array.length);
                    field.set(result, copy);
                    for (int i = 0; i < copy.length; i++) {
                        if (copy[i] instanceof Card) {
                            copy[i] = Card.createHiddenCard();
                        }
                    }
                }
            }
            return result;
        } catch (IllegalArgumentException ex) {
            throw new RuntimeException(ex);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(ex);
        } catch (CloneNotSupportedException ex) {
            throw new RuntimeException(ex);
        }
    }
}
